using System;
using System.Collections.Generic;
using Exceptions;
using System.Net;

namespace Param
{
    public class Params
    {

        private Args aArgs;

        public Params() { aArgs = new Args(); }

        public void Parse(string[] args) { aArgs.Parse(args); }

        public IPAddress GetValue(string key, IPAddress defaultValue)
        {
            return GetValue<IPAddress>(key, IPAddress.Parse, defaultValue);
        }

        public int GetValue(string key, int defaultValue)
        {
            return GetValue<int>(key, int.Parse, defaultValue);
        }

        public string GetValue(string key, string defaultValue)
        {
            return GetValue<string>(key, (string value) => { return value; }, defaultValue);
        }

        public bool GetValue(string key, bool defaultValue)
        {
            return GetValue<bool>(key, bool.Parse, defaultValue);
        }

        private T GetValue<T>(string key, Func<string, T> FuncParse, T defaultValue)
        {
            string strParam = aArgs.GetValue(key);
            if (strParam == null) return defaultValue;

            try { return FuncParse(strParam); }
            catch (Exception e)
            {
                throw new ExceptionStopApp($"输入参数错误: 不能将 \"{strParam}\" 转换为{typeof(T)}类型!", e);
            }
        }
    }
}
